package mymyoux.controls
{
	import flash.display.DisplayObject;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import mx.containers.TitleWindow;
	import mx.containers.VBox;
	import mx.controls.Button;
	import mx.controls.Label;
	import mx.events.FlexEvent;
	import mx.managers.PopUpManager;
	import flash.utils.getTimer;
	import mymyoux.events.WaitEvent;
	public class Wait extends TitleWindow
	{
		protected var v1:VBox;
		protected var textLabel:Label;
		protected var timerLabel:Label;
		protected var butCancel:Button;
		protected var interval:Number;
		protected var timer:Timer;
		protected var endTime:Number;
		protected var startTime:Number;
		protected var isPopuped:Boolean;


		public function Wait()
		{
			super();
			v1=new VBox();
			butCancel=new Button();
			butCancel.label="Annuler";
			butCancel.addEventListener(FlexEvent.BUTTON_DOWN,onCancel);
			addChild(v1);
			textLabel=new Label();
			textLabel.text="";
			timerLabel=new Label();
			timerLabel.text="";
			v1.addChild(textLabel);
			v1.addChild(timerLabel);
			v1.addChild(butCancel);
			timer=new Timer(500);
			timer.addEventListener(TimerEvent.TIMER,onTimer);
			isPopuped=false;
		}
		public function get text():String{
			return textLabel.text;
		}
		public function set text(s:String):void{
			textLabel.text=s;
		}	
		public function show(center:Boolean,modal:Boolean,parent:DisplayObject,cancelable:Boolean=true,seconds:uint=0):void{
			if(!isPopuped){
				butCancel.visible=cancelable;
				PopUpManager.addPopUp(this,parent,modal);
				
				isPopuped=true;
			}
			if(center){
					PopUpManager.centerPopUp(this);
				}
				if(seconds>0){
					startTime=getTimer();
					endTime=getTimer()+seconds*1000;
					timer.addEventListener(TimerEvent.TIMER,onTimer);
					this.timer.start();
					onTimer();
				}
		}
		public function hide():void{
			if(isPopuped){
				isPopuped=false;
				PopUpManager.removePopUp(this);
			}
		}
		protected function onTimer(e:TimerEvent=null):void{
			if(getTimer()>endTime){
				timer.stop();
				this.dispatchEvent(new WaitEvent(WaitEvent.END,WaitEvent.END));
				timerLabel.text="Veuillez patienter";
				timer.removeEventListener(TimerEvent.TIMER,onTimer);
			}else{
				var sec:Number=Math.round((endTime-getTimer())/1000);
				timerLabel.text="Prochaine tentative dans "+sec+" seconde"+((sec>1)?"s":"");
			}
		}
		protected function onCancel(e:FlexEvent):void{
			this.dispatchEvent(new WaitEvent(WaitEvent.CANCEL,WaitEvent.CANCEL));
			hide();
		}
	}
}